package com.yst.webplugin.fieldhandler;

import com.yst.spring.context.SpringContext;
import com.yst.webplugin.annotation.Command;
import com.yst.webplugin.annotation.HttpInfo;
import com.yst.webplugin.annotation.ICommand;
import com.yst.webplugin.util.ParamUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.util.*;

@Slf4j
public class BatchCommandHandler implements IFieldHandler{
    @Override
    public boolean accept(Field field) {
        return Objects.nonNull(field.getAnnotation(Command.BatchCommand.class));
    }

    @SneakyThrows
    @Transactional
    @Override
    public void handle(Field field, HttpInfo httpInfo) {
        Command.BatchCommand batchCommand=field.getAnnotation(Command.BatchCommand.class);
        List<Command> commandList= Arrays.asList(batchCommand.commands());
        SqlToyLazyDao sqlToyLazyDao= SpringContext.getContext().getBean(SqlToyLazyDao.class);
        Map<String,Object> params=httpInfo.getBodyAs(HashMap.class);
        for(Command command:commandList){
            try {
                ParamUtils.checkParams(params,command.validClass(),command.validClassGroup());
                Class<? extends ICommand> iCommand = command.executor();
                if (Objects.nonNull(iCommand)) {
                    ICommand cmdInstance = SpringContext.getContext().getBean(iCommand);
                    cmdInstance.execute(httpInfo);
                } else {
                    sqlToyLazyDao.executeSql(command.commandName(), params);
                }
            }
            catch (Exception e){
                log.error(getClass().getName()+" execute fail:{}, command:{}",e.getMessage(),command);
                throw e;
            }
        }
    }
}
